import requests

# Gogs API 配置
API_TOKEN = "eee09f0f3b758dd4ca71c9aa54e0a5c962061dbb"
GOGS_URL = "http://192.168.168.168:3000/api/v1"
USER_NAME = "wuyunbin"  # 替换为你的 Gogs 用户名

# 请求头
HEADERS = {
    "Authorization": f"token {API_TOKEN}",
    "Content-Type": "application/json",
}

def get_repos():
    """获取 Gogs 中的所有仓库"""
    print("正在获取 Gogs 中的仓库列表...")
    response = requests.get(f"{GOGS_URL}/user/repos", headers=HEADERS)
    if response.status_code != 200:
        print("无法获取仓库列表。请检查 API Token 和网络连接。")
        exit(1)
    return response.json()

def list_repos(repos):
    """列出仓库并排序"""
    print("Gogs 中的仓库列表：")
    repos_sorted = sorted(repos, key=lambda x: x["full_name"])
    for idx, repo in enumerate(repos_sorted, start=1):
        print(f"    {idx}  {repo['full_name']}")
    return repos_sorted

def delete_repo(repo_name):
    """删除指定仓库"""
    print(f"正在删除仓库: {repo_name}...")
    response = requests.delete(f"{GOGS_URL}/repos/{repo_name}", headers=HEADERS)
    if response.status_code == 204:
        print(f"仓库 {repo_name} 删除成功。")
    else:
        print(f"仓库 {repo_name} 删除失败。HTTP 状态码: {response.status_code}")

def main():
    # 获取所有仓库
    repos = get_repos()
    if not repos:
        print("没有找到任何仓库。")
        return

    # 列出仓库并排序
    repos_sorted = list_repos(repos)

    # 提示用户选择
    selection = input("请输入要删除的仓库序号（输入 -1 删除所有仓库）：").strip()
    try:
        selection = int(selection)
    except ValueError:
        print("无效的输入。请输入一个数字。")
        return

    if selection == -1:
        # 删除所有仓库
        print("你选择了删除所有仓库。")
        for repo in repos_sorted:
            delete_repo(repo["full_name"])
    else:
        # 检查选择的序号是否有效
        if selection < 1 or selection > len(repos_sorted):
            print("无效的序号。")
            return

        # 获取选择的仓库信息
        repo_name = repos_sorted[selection - 1]["full_name"]
        delete_repo(repo_name)

if __name__ == "__main__":
    main()